package com.ljx.api.interceptor;

import com.alibaba.fastjson.JSON;
import com.ljx.common.core.Result;
import com.ljx.common.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

import static com.ljx.api.constrant.GlobalConstrant.TOKEN_PASSWORD;

/**
 * @类名: LoginInterceptor
 * @描述:
 * @日期: 2020-09-07 20:56
 * @作者: 刘纪譞
 * @版本: 1.0.0
 * <p>
 * since JDK 1.8
 **/
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(request.getMethod().equals("OPTIONS")){
            log.info("aaa");
            return true;
        }
        String token = request.getHeader("token");
        log.info(request.getRequestURI());
        if (!StringUtils.isEmpty(token)) {
            String username = JwtUtils.getUsername(token);
            if (JwtUtils.verify(token, username, TOKEN_PASSWORD)) {
                log.info("bbb");
                return true;
            }
        }
        Result result=Result.fail("token不正确，请登录");
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(JSON.toJSONString(result));
      return false;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
